//
//  JYSportDailyViewController.m
//  FinderBox
//
//  Created by JiYi on 2018/10/29.
//  Copyright © 2018 JiYi. All rights reserved.
//

#import "JYSportDailyViewController.h"


#import <CoreMotion/CoreMotion.h>

@interface JYSportDailyViewController ()<FSCalendarDelegate, FSCalendarDataSource, FSCalendarDelegateAppearance, UITableViewDelegate, UITableViewDataSource, UIGestureRecognizerDelegate>{
    void * _KVOContext;
}

//  顶部视图
@property (nonatomic, strong) UIView * topView;

//  日历
@property (nonatomic, strong) FSCalendar * canlendarView;
//  标注
@property (nonatomic, strong) UIView * tipsView;

//  日程
@property (nonatomic, strong) UITableView * tableView;

//  农历的数组
@property (nonatomic, strong) NSArray * lunarChars;
//  本地的日历
@property (nonatomic, strong) NSCalendar * lunarCalendar;
//  事件数组
@property (nonatomic, strong) NSMutableArray * datesWithEvent;

@property (weak, nonatomic) UIButton *previousButton;
@property (weak, nonatomic) UIButton *nextButton;

@property (strong, nonatomic) NSCalendar *gregorian;

@property (strong, nonatomic) UIPanGestureRecognizer *scopeGesture;

//  navBarView
@property (nonatomic, strong) UIView * navHeaderView;
//  日期
@property (nonatomic, strong) UILabel * headerTitle;


//  商品数组
@property (nonatomic, strong) NSMutableArray * goodsArray;
//  日志数据
@property (nonatomic, strong) NSMutableArray * logArray;


@property (nonatomic, strong) NSMutableArray * dataSource;

@property (nonatomic,copy)NSString * sqlString;

@property (nonatomic,strong)NSDate * showDate;

@property (nonatomic,strong)CMPedometer * pedometer;

@end

@implementation JYSportDailyViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    
    //  初始化Nav视图
//    [self setupHeaderView];
    self.hbd_titleTextAttributes = @{NSForegroundColorAttributeName:UIColor.whiteColor};
    self.hbd_tintColor = UIColor.whiteColor;
    
    self.hbd_barTintColor = [UIColor jk_gradientFromColor:JYColorFromHex(0x41adf6) toColor:JYColorFromHex(0x1e53d8) withHeight:64 width:WIN_WIDTH];
    self.hbd_barShadowHidden = YES;
    
    [self setupCanlender];
    
    [self loadDataWithDate:[NSDate date]];
}

- (CMPedometer *)pedometer{
    if (!_pedometer) {
        _pedometer = [[CMPedometer alloc]init];
    }
    return _pedometer;
}

- (void)loadDataWithDate:(NSDate *)date{
    [self.dataSource removeAllObjects];
    self.showDate = date;
    long long zeroTime = [[date jk_zeroDate] timeIntervalSince1970];
    long long zero24Time = [[date jk_zero24Date] timeIntervalSince1970];
    self.sqlString = [NSString stringWithFormat:@"isEveryDay = 0 and createTime > %llu and createTime < %llu",zeroTime,zero24Time];
    NSArray * array =  [WHCSqlite query:[StepModel class] where:self.sqlString order:@"by createTime asc"];
    __weak typeof(self) weakSelf = self;
    [MBProgressHUD showActivity];
    
    if (array.count) {
        for (StepModel * model in array) {
            if (model.havStep) {
                [self.dataSource addObject:model];
            }else{
                NSDate * startDate = [NSDate dateWithTimeIntervalSince1970:model.createTime];
                NSDate * endDate = model.notDate;
                [self.pedometer queryPedometerDataFromDate:startDate toDate:endDate withHandler:^(CMPedometerData * _Nullable pedometerData, NSError * _Nullable error) {
                    NSNumber * stepNum = pedometerData.numberOfSteps;
                    if (!error) {
                        model.step = [stepNum intValue];
                        model.havStep = YES;
                        NSString * sql = [NSString stringWithFormat:@"createTime = %llu",model.createTime];
                        [WHCSqlite update:model where:sql];
                        [weakSelf.dataSource addObject:model];
                    }else{
                        model.step = 0;
                        model.havStep = NO;
                    }
                }];
            }
        }
        [GCDQueue executeInMainQueue:^{
            [MBProgressHUD hideHUD];
            [weakSelf.tableView reloadData];
        } afterDelaySecs:3];
    }else{
        [MBProgressHUD hideHUD];
        [MBProgressHUD showInfoMessage:@"没有历史记录"];
    }
    
    [self.tableView reloadData]; 
}


- (NSString*)stringFromDate:(NSDate*)date{
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSString *destDateString = [dateFormatter stringFromDate:date];
    
    return destDateString;
}
- (NSMutableArray *)dataSource {
    if (!_dataSource) {
        _dataSource = [NSMutableArray array];
    }
    return _dataSource;
}

#pragma mark - 懒加载
- (NSCalendar *)lunarCalendar {
    if (!_lunarCalendar) {
        _lunarCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierChinese];
        _lunarCalendar.locale = [NSLocale localeWithLocaleIdentifier:@"zh-CN"];
    }
    return _lunarCalendar;
}
- (NSArray *)lunarChars {
    if (!_lunarChars) {
        _lunarChars = @[@"初一",@"初二",@"初三",@"初四",@"初五",@"初六",@"初七",@"初八",@"初九",@"初十",@"十一",@"十二",@"十三",@"十四",@"十五",@"十六",@"十七",@"十八",@"十九",@"二十",@"廿一",@"廿二",@"廿三",@"廿四",@"廿五",@"廿六",@"廿七",@"廿八",@"廿九",@"三十"];
    }
    return _lunarChars;
}
//  事件
- (NSMutableArray *)datesWithEvent {
    if (!_datesWithEvent) {
        _datesWithEvent = [@[@{@"time":@"2017-12-06", @"type":@"1"}, @{@"time":@"2017-12-10", @"type":@"2"}, @{@"time":@"2017-12-20", @"type":@"3"}, @{@"time":@"2017-12-29", @"type":@"4"}] mutableCopy];
    }
    return _datesWithEvent;
}

- (void)dealloc
{
    [self.canlendarView removeObserver:self forKeyPath:@"scope" context:_KVOContext];
    NSLog(@"%s",__FUNCTION__);
}

#pragma mark - 初始化按钮
- (void)setupHeaderView {
    _navHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 64)];
    self.navigationItem.titleView = _navHeaderView;
    
    _headerTitle = [[UILabel alloc] init];
    [self.navHeaderView addSubview:_headerTitle];
    
    _headerTitle.userInteractionEnabled = YES;
    _headerTitle.text = @"2015-20";
    _headerTitle.textAlignment = NSTextAlignmentCenter;
    _headerTitle.font = [UIFont systemFontOfSize:17.0 weight:UIFontWeightLight];
    
    
    [_headerTitle mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(self.navHeaderView);
        make.size.mas_equalTo(CGSizeMake(110, 44));
    }];
    
    //  按钮
    
    UIButton *previousButton = [UIButton buttonWithType:UIButtonTypeCustom];
    previousButton.titleLabel.font = [UIFont systemFontOfSize:13.0];
    [previousButton setImage:[UIImage imageNamed:@"icon_prev"] forState:UIControlStateNormal];
    [previousButton addTarget:self action:@selector(previousClicked:) forControlEvents:UIControlEventTouchUpInside];
    [previousButton setTitle:@"上一月" forState:UIControlStateNormal];
    [previousButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [self.navHeaderView addSubview:previousButton];
    self.previousButton = previousButton;
    
    [previousButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.navHeaderView);
        make.right.equalTo(self.headerTitle.mas_left);
        make.size.mas_equalTo(CGSizeMake(120, 40));
    }];
    
    UIButton *nextButton = [UIButton buttonWithType:UIButtonTypeCustom];
    nextButton.titleLabel.font = [UIFont systemFontOfSize:13.0f];
    [nextButton setImage:[UIImage imageNamed:@"icon_next"] forState:UIControlStateNormal];
    [nextButton setTitle:@"下一月" forState:UIControlStateNormal];
    [nextButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [nextButton addTarget:self action:@selector(nextClicked:) forControlEvents:UIControlEventTouchUpInside];
    [self.navHeaderView addSubview:nextButton];
    self.nextButton = nextButton;
    
    [nextButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.navHeaderView);
        make.left.equalTo(self.headerTitle.mas_right);
        make.size.mas_equalTo(CGSizeMake(120, 40));
    }];
    
    UITapGestureRecognizer * tapGes = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(headerTitleClick)];
    [_headerTitle addGestureRecognizer:tapGes];
}

#pragma mark - 日期点击
- (void)headerTitleClick {

    
}





#pragma mark - 初始化日历
- (void)setupCanlender {
    _topView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WIN_WIDTH, 330)];
    
    _topView.backgroundColor = [UIColor whiteColor];
    
    [self.view addSubview:_topView];
    
    //  初始化日历对象
    
    CGFloat height = [[UIDevice currentDevice].model hasPrefix:@"iPad"] ? 450 : 300;
    _canlendarView = [[FSCalendar alloc] initWithFrame:CGRectMake(0, SafeAreaTopHeight, WIN_WIDTH, height)];
    _canlendarView.backgroundColor = [UIColor whiteColor];
    _canlendarView.delegate = self;
    _canlendarView.dataSource = self;
    
    _canlendarView.headerHeight = 0;
    _canlendarView.scope = FSCalendarScopeMonth;
    
    _canlendarView.appearance.subtitleFont = [UIFont systemFontOfSize:12];
    _canlendarView.placeholderType = FSCalendarPlaceholderTypeNone;
    
    _canlendarView.appearance.titleFont = [UIFont systemFontOfSize:16.0 weight:UIFontWeightRegular];
    _canlendarView.appearance.subtitleFont = [UIFont systemFontOfSize:11.0f weight:UIFontWeightLight];
    
    _canlendarView.appearance.headerMinimumDissolvedAlpha = 0;
    
    _canlendarView.appearance.caseOptions = FSCalendarCaseOptionsHeaderUsesUpperCase | FSCalendarCaseOptionsWeekdayUsesUpperCase;
    _canlendarView.appearance.weekdayTextColor = JYColorFromHex(0x333333);
    _canlendarView.appearance.headerTitleColor = [UIColor darkGrayColor];
    _canlendarView.appearance.eventDefaultColor = [UIColor colorWithRed:1 green:140/255.0 blue:0 alpha:1];
    _canlendarView.appearance.selectionColor = [UIColor colorWithRed:0 green:191/255.0 blue:1 alpha:1];
    _canlendarView.appearance.headerDateFormat = @"yyyy年MM月";
    _canlendarView.appearance.todayColor = [UIColor colorWithRed:1 green:140/255.0 blue:0 alpha:1];
    
    _canlendarView.appearance.borderRadius = 0;
    _canlendarView.appearance.headerMinimumDissolvedAlpha = 0.0;
    
    
    [self.topView addSubview:_canlendarView];
    
    
    
    //  提示
    _tipsView = [[UIView alloc] initWithFrame:CGRectMake(0, _canlendarView.frame.origin.y + _canlendarView.frame.size.height + 0, WIN_WIDTH, 30)];
    [self.topView addSubview:_tipsView];
    
    _tipsView.backgroundColor = [UIColor whiteColor];
    
    
    UIView * view1 = [self viewWithColor:JYColorFromRGB(243, 183, 183) andTitle:@"历史步数"];
    [_tipsView addSubview:view1];

    [self makeEqualWidthViews:@[view1] inView:_tipsView LRpadding:0 viewPadding:0];
    
    _tipsView.userInteractionEnabled = NO;
    
    
    [self.canlendarView addObserver:self forKeyPath:@"scope" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:_KVOContext];
    
    
    //  创建tableView
    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    [self.view addSubview:_tableView];
    
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.topView.mas_bottom);
        make.left.equalTo(self.view);
        make.right.equalTo(self.view);
        make.bottom.equalTo(self.view);
    }];
    
    _tableView.estimatedRowHeight = 0;
    _tableView.estimatedSectionFooterHeight = 0;
    _tableView.estimatedSectionHeaderHeight = 0;
    
    //  设置属性
    _tableView.backgroundColor = [UIColor colorWithRed:245/255.0 green:245/255.0 blue:245/255.0 alpha:1];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.rowHeight = 90;
    _tableView.separatorStyle = UITableViewCellSelectionStyleGray;
    _tableView.separatorInset = UIEdgeInsetsMake(0, 15, 0, 15);
    

    [_canlendarView selectDate:[_canlendarView today]];
    
    
    
    UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self.canlendarView action:@selector(handleScopeGesture:)];

//    UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self.view action:@selector(handless:)];
    panGesture.delegate = self;
    panGesture.minimumNumberOfTouches = 1;
    [self.view addGestureRecognizer:panGesture];
    self.scopeGesture = panGesture;

    [self.tableView.panGestureRecognizer requireGestureRecognizerToFail:panGesture];
    
    NSDateFormatter * dataFormate = [[NSDateFormatter alloc] init];
    [dataFormate setDateFormat:@"YYYY-MM"];
    
    NSString * dataStr = [dataFormate stringFromDate:self.canlendarView.today];
    
    self.headerTitle.text = dataStr;
    
    self.tableView.contentInset = UIEdgeInsetsMake(5, 0, 0, 0);
}

- (UIView *)viewWithColor:(UIColor *)color andTitle:(NSString *)title {
    UIView * view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WIN_WIDTH, 30)];
    
    //  色块
    UIView * colorView = [[UIView alloc] init];
    [view addSubview:colorView];
    
    colorView.backgroundColor = color;
    
    //  文字
    UILabel * label = [[UILabel alloc] init];
    [view addSubview:label];
    
    label.text = title;
    label.font = [UIFont systemFontOfSize:12];
    label.textColor = [UIColor blackColor];
    
    //    [colorView mas_makeConstraints:^(MASConstraintMaker *make) {
    //        make.centerY.equalTo(view);
    //        make.left.equalTo(view.mas_right).offset(10);
    //        make.size.mas_equalTo(CGSizeMake(20, 20));
    //    }];
    
    colorView.clipsToBounds = YES;
    colorView.layer.cornerRadius = 4;
    
    //    [label mas_makeConstraints:^(MASConstraintMaker *make) {
    //        make.centerY.equalTo(view);
    //        make.left.equalTo(colorView.mas_right).offset(5);
    //        make.right.equalTo(view);
    //        make.bottom.equalTo(view);
    //    }];
    
    
    
    colorView.frame = CGRectMake(10, 5, 20, 20);
    label.frame  = CGRectMake(40, 0, view.frame.size.width - 50, view.frame.size.height);
    
    return view;
}

#pragma mark - 等宽登高设置
-(void)makeEqualWidthViews:(NSArray *)views inView:(UIView *)containerView LRpadding:(CGFloat)LRpadding viewPadding :(CGFloat)viewPadding
{
    UIView *lastView;
    for (UIView *view in views) {
        [containerView addSubview:view];
        if (lastView) {
            [view mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.equalTo(containerView).offset(0);
                make.bottom.equalTo(containerView).offset(0);
                make.left.equalTo(lastView.mas_right).offset(viewPadding);
                make.width.equalTo(lastView);
            }];
        }else
        {
            [view mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.equalTo(containerView).offset(LRpadding);
                make.top.equalTo(containerView).offset(0);
                make.bottom.equalTo(containerView).offset(0);
            }];
        }
        lastView=view;
    }
    [lastView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(containerView).offset(-LRpadding);
    }];
}

- (void)handless:(UIPanGestureRecognizer *) ges{
    
}

- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer
{
    BOOL shouldBegin = self.tableView.contentOffset.y <= -self.tableView.contentInset.top;
    if (shouldBegin) {
        CGPoint velocity = [self.scopeGesture velocityInView:self.view];
        switch (self.canlendarView.scope) {
            case FSCalendarScopeMonth:
                return velocity.y < 0;
            case FSCalendarScopeWeek:
                return velocity.y > 0;
        }
    }
    return shouldBegin;
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
    
}


- (void)previousClicked:(id)sender
{
    NSDate *currentMonth = self.canlendarView.currentPage;
    NSDate *previousMonth = [self.gregorian dateByAddingUnit:NSCalendarUnitMonth value:-1 toDate:currentMonth options:0];
    [self.canlendarView setCurrentPage:previousMonth animated:YES];
}

- (void)nextClicked:(id)sender
{
    NSDate *currentMonth = self.canlendarView.currentPage;
    NSDate *nextMonth = [self.gregorian dateByAddingUnit:NSCalendarUnitMonth value:1 toDate:currentMonth options:0];
    [self.canlendarView setCurrentPage:nextMonth animated:YES];
}


#pragma mark - tableView代理
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataSource.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString * ID = @"StepListCell";
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:ID];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    StepModel * model = self.dataSource[indexPath.row];
    NSString * aTime = [[NSDate dateWithTimeIntervalSince1970:model.createTime] jk_stringWithFormat:@"yyyy-MM-dd hh:mm"];
    NSString * bTime = [model.notDate jk_stringWithFormat:@"hh:mm"];
    cell.textLabel.font = [UIFont systemFontOfSize:14.0f];
    cell.textLabel.text = [NSString stringWithFormat:@"%@-%@",aTime,bTime];
    cell.detailTextLabel.text = [NSString stringWithFormat:@"%ld步",model.step];
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
 
    static NSString * ID = @"StepListCell";
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:ID];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    StepModel * model = self.dataSource[indexPath.section];
    NSString * aTime = [[NSDate dateWithTimeIntervalSince1970:model.createTime] jk_stringWithFormat:@"yyyy-MM-dd hh:mm"];
    NSString * bTime = [model.notDate jk_stringWithFormat:@"hh:mm"];
    cell.textLabel.font = [UIFont systemFontOfSize:14.0f];
    cell.textLabel.text = [NSString stringWithFormat:@"%@-%@",aTime,bTime];
    cell.detailTextLabel.text = [NSString stringWithFormat:@"%ld步",model.step];
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
//
//    JYDaliyHeaderView * header = [[JYDaliyHeaderView alloc] init];
//
//    if (section == 0) {
//        header.titleLabel.text = @"当日配送";
//
//    }else if (section == 2) {
//        header.titleLabel.text = @"订单日志";
//    }else if (section == 1) {
//        return [UIView new];
//    }
//
//    header.backgroundColor = [UIColor whiteColor];
//    return header;
    return nil;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.01f;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.01f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 45.0f;
}

#pragma mark - 日历的代理
#pragma mark - <FSCalendarDelegate>

#pragma mark - 日历的代理方法
//  改变日历的frame
- (void)calendar:(FSCalendar * __nonnull)calendar boundingRectWillChange:(CGRect)bounds animated:(BOOL)animated {
    calendar.frame = (CGRect){calendar.frame.origin, bounds.size};
    //  CGRectMake(0, _tipsView.frame.origin.y + _tipsView.frame.size.height + 80, Width, Height - _tipsView.frame.size.height - _tipsView.frame.origin.y - 64)
    
    _tableView.frame = CGRectMake(0, _canlendarView.frame.origin.y + _canlendarView.frame.size.height + 30, WIN_WIDTH, WIN_HEIGHT - _canlendarView.frame.size.height - _canlendarView.frame.origin.y - 90);
    //  让日历显示最上面的日记
    _tableView.contentOffset = CGPointMake(0, 0);
    
    
    _tipsView.frame = CGRectMake(0, _canlendarView.frame.origin.y + _canlendarView.frame.size.height + 0, WIN_WIDTH, 30);
}

//  日历页面变化时，改变顶部月份
- (void)calendarCurrentPageDidChange:(FSCalendar *)calendar {
    NSDateFormatter * dataFormate = [[NSDateFormatter alloc] init];
    [dataFormate setDateFormat:@"YYYY-MM"];
    
    NSString * dataStr = [dataFormate stringFromDate:calendar.currentPage];
    
    self.headerTitle.text = dataStr;
    
}

//  初始化Cell，显示事件颜色
- (void)calendar:(FSCalendar *)calendar willDisplayCell:(FSCalendarCell *)cell forDate:(NSDate *)date atMonthPosition: (FSCalendarMonthPosition)monthPosition
{
    // FSCalendarMonthPositionCurrent
    // FSCalendarMonthPositionPrevious
    [self configureCell:cell forDate:date atMonthPosition:monthPosition];
}


- (void)configureCell:(__kindof FSCalendarCell *)cell forDate:(NSDate *)date atMonthPosition:(FSCalendarMonthPosition)position
{
#pragma mark - 暂时这样操作
    
    NSDateFormatter * dataFormate = [[NSDateFormatter alloc] init];
    [dataFormate setDateFormat:@"YYYY-MM-dd"];
    
    NSString * dataStr = [dataFormate stringFromDate:date];
    
    for (NSDictionary * dict in self.datesWithEvent) {
        
        
        if ([dataStr isEqualToString:dict[@"time"]]) {
            if ([dict[@"type"] isEqualToString:@"1"]) {
                //  变更产品
                cell.shapeLayer.fillColor  = JYColorFromRGB(243, 183, 183).CGColor;
            }else if ([dict[@"type"] isEqualToString:@"2"]) {
                //  暂停订单
                cell.shapeLayer.fillColor  = JYColorFromRGB(252, 227, 127).CGColor;
            }else if ([dict[@"type"] isEqualToString:@"3"]) {
                //  停止订单
                cell.shapeLayer.fillColor  = JYColorFromRGB(141, 193, 250).CGColor;
            }else if ([dict[@"type"] isEqualToString:@"4"]) {
                //  投诉订单
                cell.shapeLayer.fillColor  = JYColorFromRGB(204, 167, 247).CGColor;
            }
            
        }
    }
    
    //  看看是不是选择的日期
    if ([date isEqual:self.canlendarView.selectedDate]) {
        cell.shapeLayer.fillColor = [UIColor colorWithRed:0 green:191/255.0 blue:1 alpha:1].CGColor;
    }
}

//  反选日期时，绘制颜色
- (void)calendar:(FSCalendar *)calendar didDeselectDate:(NSDate *)date atMonthPosition:(FSCalendarMonthPosition)monthPosition {
    
    //  根据日期和位置，确定出Cell
    FSCalendarCell * cell =  [self.canlendarView cellForDate:date atMonthPosition:monthPosition];
    
    NSDateFormatter * dataFormate = [[NSDateFormatter alloc] init];
    [dataFormate setDateFormat:@"YYYY-MM-dd"];
    
    NSString * dataStr = [dataFormate stringFromDate:date];
    
    for (NSDictionary * dict in self.datesWithEvent) {
        
        if ([dataStr isEqualToString:dict[@"time"]]) {
            if ([dict[@"type"] isEqualToString:@"1"]) {
                //  变更产品
                cell.shapeLayer.fillColor  = JYColorFromRGB(243, 183, 183).CGColor;
            }else if ([dict[@"type"] isEqualToString:@"2"]) {
                //  暂停订单
                cell.shapeLayer.fillColor  = JYColorFromRGB(252, 227, 127).CGColor;
            }else if ([dict[@"type"] isEqualToString:@"3"]) {
                //  停止订单
                cell.shapeLayer.fillColor  = JYColorFromRGB(141, 193, 250).CGColor;
            }else if ([dict[@"type"] isEqualToString:@"4"]) {
                //  投诉订单
                cell.shapeLayer.fillColor  = JYColorFromRGB(204, 167, 247).CGColor;
            }
            
        }
    }
    //    //  看看是不是选择的日期
    //    if ([date isEqual:self.canlendarView.selectedDate]) {
    //        cell.shapeLayer.fillColor = [UIColor colorWithRed:0 green:191/255.0 blue:1 alpha:1].CGColor;
    //    }
    
}

- (void)calendar:(FSCalendar *)calendar didSelectDate:(NSDate *)date atMonthPosition:(FSCalendarMonthPosition)monthPosition{
    //  请求数据，更换列表状态
    [SVProgressHUD dismiss];
    
    
    [self.goodsArray removeAllObjects];
    [self.logArray removeAllObjects];
    
    [self.tableView reloadData];
    
//    [self getDaliyDataWithTime:[self stringFromDate:date]];
    [self loadDataWithDate:date];
}


//  打开农历显示
- (NSString *)calendar:(FSCalendar * __nonnull)calendar subtitleForDate:(NSDate * __nonnull)date {
    if (1) {
        NSInteger day = [self.lunarCalendar components:NSCalendarUnitDay fromDate:date].day;
        return self.lunarChars[day-1];
    }
    return nil;
}
//  自定义今天的显示方式
- (NSString *)calendar:(FSCalendar *)calendar titleForDate:(NSDate *)date
{
    return [calendar isDateInToday:date] ? @"今" : nil;
}
//  选中日期的处理事件
- (void)calendar:(FSCalendar *)calendar didSelectDate:(NSDate *)date
{
    //    NSLog(@"did select date %@",[calendar stringFromDate:date format:@"yyyy/MM/dd"]);
    //  此时的date就是选中的天数
    //    [self getDateFromSelectedDay:date withCalendar:calendar];
    
}
- (NSInteger)calendar:(FSCalendar *)calendar numberOfEventsForDate:(NSDate *)date
{
    //  格式化一下
    NSDateFormatter * dataFormate = [[NSDateFormatter alloc] init];
    [dataFormate setDateFormat:@"YYYY-MM-dd"];
    
    NSString * dataStr = [dataFormate stringFromDate:date];
    
    for (NSDictionary * dict in self.datesWithEvent) {
        if ([dict[@"time"] isEqualToString:dataStr]) {
            return YES;
        }
    }
    
    //   显示事件的圆点
    return NO;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
